<?php
/**
 * Gere le controle de la plateforme webnews
 * @author Etienne AUDOUIN <etienne.audouin@ingesup.com>
 * @author Adrien MARIANELLI <adrien.marianelli@ingesup.com>
 * @version 1.0
 * @package controllers
 * @subpackage webnews
 */
class webnews extends CI_Controller {
    /**
     * Point d'entree du controller
     * redirige vers le contact Manager
     * @see contactManager
    */
    public function index() {
        redirect('webnews/contactManager');
    }


    /**
     * Menu pour la gestion des newsletters.
     * @see createNewsletter
     * @see readNewsletter
     * @see updateNewsletter
     * @see doUpdateNewsLetter
     * @see deleteNewsletter
     * @see sendNewsletter
     */
    public function newsletterManager() {
        $this->load->view('webnews/header');
        $this->load->view('webnews/newsletterManager');
        $this->load->view('webnews/footer');
    }


    /**
     * Menu pour la gestion des contacts et des mailing lists.
     * @see createContact
     * @see searchContact
     * @see updateContact
     * @see doUpdateContact
     * @see deleteContact
     *
     * @see createMailinglist
     * @see searchMailinglist
     * @see updateMailinglist
     * @see addContactTo
     * @see deleteContactFrom
     * @see deleteMailinglist
     */
    public function contactManager() {
        $this->load->view('webnews/header');
        $this->load->view('webnews/contactManager');
        $this->load->view('webnews/footer');
    }

    /**
     * Cree un nouveau contact
     * {@source}
     */
    public function createContact() {
        $this->load->view('webnews/header');

        $this->form_validation->set_rules('contactName', 'Name', 'required');
        $this->form_validation->set_rules('contactFirstName', 'First name', 'required');
        $this->form_validation->set_rules('contactMail', 'Mail', 'required');

        if ($this->form_validation->run() == FALSE)
            $this->load->view('webnews/contact/create');
        else {
            $this->load->model('contact_model', 'contactManager');
            $name = $this->input->post('contactName', TRUE);
            $first_name = $this->input->post('contactFirstName', TRUE);
            $mail = $this->input->post('contactMail', TRUE);

            $this->contactManager->create($name, $first_name, $mail);
            redirect('webnews/contactManager');
        }

        $this->load->view('webnews/footer');
    }

    /**
     * Cherche un contact a partir de son nom, de son nom de famille, ou de son adresse mail.
     * {@source}
     */
    public function searchContact() {
        $this->load->view('webnews/header');

        $this->form_validation->set_rules('contactSearch', 'Contact Search', 'required');

        if ($this->form_validation->run() == FALSE)
            $this->load->view('webnews/contact/search');
        else {
            $this->load->model('contact_model', 'contactManager');
            $contacts = $this->contactManager->searchContact($this->input->post('contactSearch', TRUE));
            $this->load->view('webnews/contact/search');
            if (count($contacts)) {
                $data['contacts'] = $contacts;
                $this->load->view('tools/displayContacts', $data);
            }
        }
        $this->load->view('webnews/footer');
    }

    /**
     * Presente un formulaire pour mettre a jour les informations liees a un contact
     * {@source}
     */
    public function updateContact() {
        $this->load->model('contact_model', 'contactManager');

        $this->load->view('webnews/header');

        $contacts = $this->contactManager->readAll();

        $contactsFinal = array();
        foreach ($contacts as $contact) {
            $contact = get_object_vars($contact);
            $contactsFinal[$contact['id']] = $contact;
        }

        $data['contacts'] = $contactsFinal;
        $data['list'] = true;

        $this->load->view('webnews/contact/update', $data);

        $this->load->view('webnews/footer');
    }

    /**
     * Met a jour les informations liees a un contact
     * {@source}
     */
    public function doUpdateContact() {
        $this->form_validation->set_rules('contactFirstName', 'Contact First Name', 'required');
        $this->form_validation->set_rules('contactName', 'Contact Name', 'required');
        $this->form_validation->set_rules('contactMail', 'Contact Mail', 'required');

        if ($this->form_validation->run() == true) {

            $first_name = $this->input->post('contactFirstName', TRUE);
            $name = $this->input->post('contactName', TRUE);
            $mail = $this->input->post('contactMail', TRUE);

            $this->load->model('contact_model', 'contactManager');
            $this->contactManager->update($first_name, $name, $this->uri->segment(3), $mail);
        }
        redirect('webnews/updateContact');
    }

    /**
     * Supprime un contact
     * {@source}
     */
    public function deleteContact() {
        $this->load->model('contact_model', 'contactManager');
        $this->load->model('mailinglist_model', 'mailManager');

        $this->form_validation->set_rules('dropdown_deleteContact', 'Contact Id', 'required');

        $this->load->view('webnews/header');
        $data['contacts'] = $this->contactManager->readAll();
        if ($this->form_validation->run() == FALSE)
            $this->load->view('webnews/contact/delete', $data);
        else {
            $idContact = $this->input->post('dropdown_deleteContact');
            $this->contactManager->delete($idContact);
            foreach ($this->mailManager->trace($idContact) as $list) {
                $name = $list->name;
                $contacts = explode(':', $list->id_contacts);
                unset($contacts[array_search($idContact, $contacts)]);
                $id = $list->id;
                if (!count($contacts))
                    $this->mailManager->delete($list->id);
                else
                    $this->mailManager->update($id, implode(':', $contacts), $name);
            }
            redirect('webnews/contactManager');
        }
        $this->load->view('webnews/footer');
    }

    /**
     * Cree une nouvelle liste de diffusion
     * {@source}
     */
    public function createMailinglist() {
        $this->load->view('webnews/header');

        $this->form_validation->set_rules('input_listName', 'Name', 'required');
        $this->form_validation->set_rules('multi_listContact', 'Id Contacts', 'required');

        if ($this->form_validation->run() == FALSE) {
            $this->load->model('contact_model', 'contactManager');
            $data['contacts'] = $this->contactManager->readAll();
            $this->load->view('webnews/mailinglist/create', $data);
        } else {
            $this->load->model('mailinglist_model', 'mailManager');
            $this->mailManager->create($this->input->post('input_listName', TRUE), $this->input->post('multi_listContact', TRUE));
            redirect('webnews/contactManager');
        }

        $this->load->view('webnews/footer');
    }

    /**
     * Presente toutes les informations contact au sein d'une liste de diffusion
     * {@source}
     */
    public function searchMailinglist() {
        $this->load->model('mailinglist_model', 'mailManager');
        $this->load->view('webnews/header');

        $this->form_validation->set_rules('select_list', 'List', 'required');
        if ($this->form_validation->run() == FALSE)
            $this->load->view('webnews/mailinglist/search', array('lists' => $this->mailManager->readAll()));
        else {
            $this->load->model('contact_model', 'contactManager');

            $this->load->view('webnews/mailinglist/search', array('lists' => $this->mailManager->readAll()));

            $contacts = array();
            foreach (explode(":", $this->input->post('select_list')) as $id) {
                if (count($this->contactManager->read($id))) {
                    $contact = array_pop($this->contactManager->read($id));

                    $contacts[$contact->id] = array(
                        'name' => $contact->name,
                        'firstName' => $contact->first_name,
                        'mail' => $contact->mail);
                }
            }
            if (count($contacts)) {
                $data['contacts'] = $contacts;
                $this->load->view('tools/displayContacts', $data);
            }
        }
        $this->load->view('webnews/footer');
    }

    /**
     * Met a jour une liste de diffusion
     * {@source}
     */
    public function updateMailinglist() {
        $this->load->model('mailinglist_model', 'mailManager');

        $this->load->view('webnews/header');
        $this->form_validation->set_rules('select_list', 'List', 'required');
        if ($this->form_validation->run() == FALSE)
            $this->load->view('webnews/mailinglist/update', array('lists' => $this->mailManager->readAll()));
        else {
            $this->load->model('contact_model', 'contactManager');
            $this->load->view('webnews/mailinglist/update', array('lists' => $this->mailManager->readAll()));
            $contacts = array();
            $listInfo = explode('_', $this->input->post('select_list'));
            foreach (explode(":", $listInfo[1]) as $id) {
                $buffer = $this->contactManager->read($id);
                $contact = $buffer[0];

                $contacts[$contact->id] = array(
                    'id' => $contact->id,
                    'name' => $contact->name,
                    'firstName' => $contact->first_name,
                    'mail' => $contact->mail);
            }
            // Add a contact
            $data_add = array(
                'contacts' => $contacts,
                'contactsToAdd' => $this->contactManager->readAll(),
                'listInfo' => $listInfo
            );
            $this->load->view('webnews/mailinglist/add', $data_add);
            // Delete contact
            if (count($contacts)) {
                $data['contacts'] = $contacts;
                $data['title'] = 'Delete contact';
                $data['button'] = 'Delete';
                $data['url'] = 'webnews/deleteContactFrom';
                $this->load->view('tools/displayCheckableContacts', $data);
            }
        }
        $this->load->view('webnews/footer');
    }

    /**
     * Ajoute un contact a une liste de difusion existante
     * {@source}
     */
    public function addContactTo() {
        $this->load->model('mailinglist_model', 'mailManager');

        $buffer = $this->input->post('list');
        $list = $this->mailManager->read($buffer[0]);

        $toAdd = $this->input->post('multi_listContact');
        $id = $list[0]->id;
        $contacts = explode(':', $list[0]->id_contacts);
        $name = $list[0]->name;

        foreach ($toAdd as $new) {
            $add = TRUE;
            foreach ($contacts as $contact) {
                if ($contact == $new)
                    $add = FALSE;
            }
            if ($add == TRUE)
                array_push($contacts, $new);
        }

        $this->mailManager->update($id, implode(":", $contacts), $name);
        redirect('webnews/contactManager');
    }

    /**
     * Supprime un contact d'une liste de diffusion existante
     * {@source}
     */
    public function deleteContactFrom() {
        $this->load->model('mailinglist_model', 'mailManager');
        $buffer = $this->input->post('list');
        $list = $this->mailManager->read($buffer[0]);

        $toRemove = $this->input->post('check_contact');
        $id = $list[0]->id;
        $contacts = explode(':', $list[0]->id_contacts);
        $name = $list[0]->name;

        foreach ($toRemove as $deleteMe) {
            $key = array_search($deleteMe, $contacts);
            unset($contacts[$key]);
        }

        $this->mailManager->update($id, implode(":", $contacts), $name);
        redirect('webnews/contactManager');
    }

    /**
     * Supprime une liste de diffusion
     * {@source}
     */
    public function deleteMailinglist() {
        $this->load->model('mailinglist_model', 'mailManager');
        $this->load->view('webnews/header');

        $this->form_validation->set_rules('select_list', 'List', 'required');
        if ($this->form_validation->run() == FALSE)
            $this->load->view('webnews/mailinglist/delete', array('lists' => $this->mailManager->readAll()));
        else {
            $this->mailManager->delete($this->input->post('select_list'));
            redirect('webnews/contactManager');
        }
        $this->load->view('webnews/footer');
    }

    /**
     * Cree une nouvelle newsletter
     * {@source}
     */
    public function createNewsletter() {
        $this->load->model('mailinglist_model', 'mailManager');

        $this->load->view('webnews/header');

        $this->form_validation->set_rules('newsletterBody', 'Body', 'required');
        $this->form_validation->set_rules('multi_mailingLists', 'Mailinglists', 'required');

        if ($this->form_validation->run() == FALSE)
            $this->load->view('webnews/newsletter/create', array('lists' => $this->mailManager->readAll()));
        else {
            $this->load->model('newsletter_model', 'newsletterManager');
            $title = $this->input->post('newsletterTitle', TRUE);
            $body = $this->input->post('newsletterBody', TRUE);
            $signature = $this->input->post('newsletterSignature', TRUE);
            $mailinglists = $this->input->post('multi_mailingLists', TRUE);
            $this->newsletterManager->create($body, $mailinglists, $title, $signature);
            redirect('webnews/newsletterManager');
        }

        $this->load->view('webnews/footer');
    }

    /**
     * Consultation des newsletters existantes
     * {@source}
     */
    public function readNewsletter() {
        $this->load->model('newsletter_model', 'newsletterManager');
        $this->load->model('mailinglist_model', 'mailManager');

        $this->load->view('webnews/header');
        $newsletters = $this->newsletterManager->readall();

        $newslettersFinal = array();
        foreach ($newsletters as $newsletter) {
            $newsletter = get_object_vars($newsletter);
            $newslettersFinal[$newsletter['id']] = $newsletter;
        }
        $titles = array();
        $titles['default'] = '<h1>Choose one</h1>';
        foreach ($newslettersFinal as $newsletter) {
            $titles[$newsletter['id']] = $newsletter['title'];
        }
        $data['newsletters'] = $newslettersFinal;
        $data['titles'] = $titles;
        $lists = $this->mailManager->readAll();
        $listsFinal = array();
        foreach ($lists as $list) {
            $list = get_object_vars($list);
            $listsFinal[$list['id']] = $list;
        }
        $data['lists'] = $listsFinal;
        if ($this->input->post('select_newsletter', TRUE) != false) {
            $data['idLetter'] = $this->input->post('select_newsletter', TRUE);
            $this->load->view('webnews/newsletter/read', $data);
        } else {
            $this->load->view('webnews/newsletter/read', $data);
        }
        $this->load->view('webnews/footer');
    }

    /**
     * Presente un formulaire de mise a jour de newsletter
     * {@source}
     */
    public function updateNewsletter() {
        $this->load->model('newsletter_model', 'newsletterManager');
        $this->load->model('mailinglist_model', 'mailManager');

        $this->load->view('webnews/header');
        $newsletters = $this->newsletterManager->readall();

        $newslettersFinal = array();
        foreach ($newsletters as $newsletter) {
            $newsletter = get_object_vars($newsletter);
            $newslettersFinal[$newsletter['id']] = $newsletter;
        }
        $titles = array();
        $titles['default'] = '<h1>Choose one</h1>';
        foreach ($newslettersFinal as $newsletter) {
            $titles[$newsletter['id']] = $newsletter['title'];
        }
        $data['newsletters'] = $newslettersFinal;
        $data['titles'] = $titles;

        $lists = $this->mailManager->readAll();
        $listsFinal = array();
        foreach ($lists as $list) {
            $list = get_object_vars($list);
            $listsFinal[$list['id']] = $list;
        }
        $data['lists'] = $listsFinal;

        if ($this->input->post('select_newsletter', TRUE) != false) {
            $data['idLetter'] = $this->input->post('select_newsletter', TRUE);
            $this->load->view('webnews/newsletter/update', $data);
        } else {
            $this->load->view('webnews/newsletter/update', $data);
        }
        $this->load->view('webnews/footer');
    }

    /**
     * Met a jour une newsletter
     * {@source}
     */
    public function doUpdateNewsLetter() {
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('content', 'Letter', 'required');

        if ($this->form_validation->run() == true) {

            $title = $this->input->post('title', TRUE);
            $content = $this->input->post('content', TRUE);
            $signature = $this->input->post('signature', TRUE);
            $mailinglists = $this->input->post('multi_mailingLists', TRUE);

            $this->load->model('newsletter_model', 'newsletterManager');
            $this->newsletterManager->update($mailinglists, $signature, $content, $title, $this->uri->segment(3));
        }
        redirect('webnews/updateNewsletter');
    }

    /**
     * Supprime une newsletter
     * {@source}
     */
    public function deleteNewsletter() {
        $this->load->model('newsletter_model', 'newsletterManager');

        $this->form_validation->set_rules('dropdown_deleteNewsletter', 'Newsletter', 'required');

        $this->load->view('webnews/header');

        $data['newsletters'] = $this->newsletterManager->readAll();
        if ($this->form_validation->run() == FALSE)
            $this->load->view('webnews/newsletter/delete', $data);
        else {
            $idNewsletter = $this->input->post('dropdown_deleteNewsletter');
            $this->newsletterManager->delete($idNewsletter);
            redirect('webnews/newsletterManager');
        }
        $this->load->view('webnews/footer');
    }

    /**
     * Envoie d'une newsletter aux listes de diffusion concernees
     * {@source}
     */
    public function sendNewsletter() {
        $this->load->model('newsletter_model', 'newsletterManager');
        $newsletters = $this->newsletterManager->readall();

        $this->load->view('webnews/header');
        $this->form_validation->set_rules('select_newsletter', 'Newsletter', 'required');
        if ($this->form_validation->run() == FALSE) {
            $data['newsletters'] = $newsletters;
            $this->load->view('webnews/newsletter/send', $data);
        } else {
            $this->load->model('mailinglist_model', 'mailManager');
            $this->load->model('contact_model', 'contactManager');

            $newsletter = array_pop($this->newsletterManager->read($this->input->post('select_newsletter')));

            $mailingLists = explode(':', $newsletter->id_mailinglists);
            foreach ($mailingLists as $listId) {
                $list = array_pop($this->mailManager->read($listId));
                $contacts = explode(':', $list->id_contacts);
                foreach ($contacts as $contactId) {
                    $contact = array_pop($this->contactManager->read($contactId));

                    $this->load->library('email');

                    $this->email->from('newsletter@webnews.com', 'Webnews');
                    $this->email->to($contact->mail);
                    $this->email->subject('Newsletter ');
                    $this->email->message(
                            '<h1>'.$newsletter->title.'</h1>'.
                            '<p>'.$newsletter->content.'</p>'.
                            '<p><small>'.$newsletter->signature.'</small></p>');
                    $this->email->send();
                }
            }
            redirect('webnews/newsletterManager');
        }
    }
}
?>
